import org.w3c.dom.traversal.TreeWalker;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * Creat by TanLei
 * Description:
 * User:86183
 * Date:2022-05-15
 * Time:9:26
 */
class MyTimer{
    static class Task implements Comparable<Task>{
        private Runnable runnable;
        private long time;

        public Task(Runnable runnable, long after) {
            this.runnable = runnable;
            this.time = System.currentTimeMillis()+after;
        }
        public void run(){
            runnable.run();
        }

        @Override
        public int compareTo(Task o) {
            return (int) (this.time-o.time);
        }
    }
    private PriorityBlockingQueue<Task> tasks = new PriorityBlockingQueue<>();


    public void schedule(Runnable runnable,long after){
        Task task = new Task(runnable,after);
        tasks.put(task);
    }
    private Object locker = new Object();
    public MyTimer(){
        Thread t = new Thread(()->{
            while (true){
                try {
                    Task task = tasks.take();
                    long curTime = System.currentTimeMillis();
                    if(curTime < task.time){
                        tasks.put(task);
                        synchronized(locker){
                            locker.wait(task.time-curTime);
                        }
                    }else{
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class Demo24 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        },3000);
        System.out.println("main");
    }
}
